package net.qiqbframework.messaging.annotation;

import net.qiqbframework.messaging.Message;

import javax.annotation.Nonnull;
import java.lang.reflect.Executable;
import java.util.Optional;

import static net.qiqbframework.common.utils.AnnotationUtil.findAnnotationAttributes;

public class AnnotatedMessageHandlingMemberFactory implements MessageHandlingMemberFactory {

    @SuppressWarnings("unchecked")
    @Override
    public <T> Optional<MessageExecutableHandler> createHandler(@Nonnull Class<T> declaringType,
                                                                @Nonnull Executable executable,
                                                                @Nonnull HandlerParameterResolverFactory parameterResolverFactory
            , @Nonnull HandlerAttributesPostProcessor handlerAttributesPostProcessor) {
        return findAnnotationAttributes(executable, MessageHandler.class)
                .map(attr -> new AnnotatedMessageExecutableHandler(
                        executable,
                        (Class<? extends Message<?>>) attr.getOrDefault("messageType", Message.class),
                        (Class<? extends Message<?>>) attr.getOrDefault("payloadType", Object.class),
                        parameterResolverFactory, handlerAttributesPostProcessor));
    }
}
